package api

import (
	"log"
	"net/http"
	"sort"

	"battle/user"
)

// 路由信息
type RouteInfo struct {
	Method string
	Path   string
}

// GetRegisteredRoutes 返回所有注册的路由
func GetRegisteredRoutes(mux *http.ServeMux) []RouteInfo {
	routes := []RouteInfo{
		{"POST", "/api/user/register"},
		{"POST", "/api/user/login"},
		{"GET", "/api/user/status"},
		{"POST", "/api/user/logout"},
	}

	sort.Slice(routes, func(i, j int) bool {
		if routes[i].Path == routes[j].Path {
			return routes[i].Method < routes[j].Method
		}
		return routes[i].Path < routes[j].Path
	})

	return routes
}

// LogRoutes 记录所有已注册的路由
func LogRoutes(routes []RouteInfo) {
	log.Println("已注册的API接口:")
	for _, route := range routes {
		log.Printf("  %s %s", route.Method, route.Path)
	}
}

// SetupRoutes 配置所有API路由
func SetupRoutes(userHandler *user.Handler, authMiddleware *user.AuthMiddleware) http.Handler {
	// 使用Go 1.22新的ServeMux
	mux := http.NewServeMux()

	// 用户管理API
	mux.HandleFunc("POST /api/user/register", userHandler.Register)
	mux.HandleFunc("POST /api/user/login", userHandler.Login)

	// 受保护的API
	mux.HandleFunc("GET /api/user/status", authMiddleware.Authenticate(http.HandlerFunc(userHandler.Status)).ServeHTTP)
	mux.HandleFunc("POST /api/user/logout", authMiddleware.Authenticate(http.HandlerFunc(userHandler.Logout)).ServeHTTP)

	// 获取并记录所有路由
	routes := GetRegisteredRoutes(mux)
	LogRoutes(routes)

	return mux
}
